Hi everyone,
I have a table Sales and I need to calculate the running total SaleAmount for each day. How can I write this query?
home / developersection / forums / sql query to calculate running total in sql server
Hi everyone,
I have a table Sales and I need to calculate the running total SaleAmount for each day. How can I write this query?
Ravi Vishwakarma
16-Jul-2024To calculate a running total in SQL Server, you can use the
SUMfunction along with theOVERclause.Here’s an example query that calculates a running total of the
Amountcolumn in a table calledTransactions:Example Table Schema
Assume you have a table named
Transactionswith the following schema:Insert data to Table
Sample Query
Here's how you can calculate the running total:
Explanation:
SELECT TransactionID, TransactionDate, Amount: Selects the columns to display.SUM(Amount) OVER (ORDER BY TransactionDate) AS RunningTotal:SUM(Amount)calculates the sum of theAmountcolumn.OVER (ORDER BY TransactionDate)specifies the order in which the rows are processed. It calculates the running total for each row in the order ofTransactionDate.AS RunningTotalnames the calculated column asRunningTotal.FROM Transactions: Specifies the table to query.ORDER BY TransactionDate: Orders the final result set byTransactionDate.This query will produce a result set with each row showing the
TransactionID,TransactionDate,Amount, and theRunningTotalup to that row, ordered byTransactionDate.Or
This query will produce a result set with each row showing the
TransactionDate, and theRunningTotalup to that row.Read more
Describe Common Table Expressions (CTEs) in SQL server.
How to Join Multiple Tables and Retrieve Specific Columns in SQL Server?
Implement row-level security in SQL Server to restrict access to data to users.